package io.github.bigbird0101.youyishi.spring.bean.load.statistics;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;

/**
 * <p> BeanLazyLoadBeanDefinitionFactory </p>
 *
 * @author fupengpeng
 * @version 1.0
 * @date 2025/6/9 9:09
 */
public class BeanLazyLoadBeanDefinitionFactory implements BeanFactoryPostProcessor {
    static String userHome = System.getProperty("user.home");
    static File configFile;
    static Properties properties;

    static {
        configFile = new File(userHome, ".youyishi/spring-bean.properties");
        if (!configFile.exists()) {
            configFile.getParentFile().mkdirs();
            try {
                configFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            properties = new Properties();
            properties.load(Files.newInputStream(configFile.toPath()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String openLazy = properties.getProperty("openLazy");
        if ("true".equals(openLazy)) {
            System.out.println("开启懒加载");
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws org.springframework.beans.BeansException {
        String openLazy = properties.getProperty("openLazy");
        String lazyPackageFilter = properties.getProperty("lazyPackageFilter");
        String lazyClassFilter = properties.getProperty("lazyClassFilter");
        String lazyBeanNameFilter = properties.getProperty("lazyBeanNameFilter");
        if (!"true".equals(openLazy)) {
            return;
        }
        // 拆分配置项并清理空格
        if (StringUtils.hasText(lazyPackageFilter)) {
            String[] filters = lazyPackageFilter.trim().split("\\s*,\\s*");
            String[] beanNames = configurableListableBeanFactory.getBeanDefinitionNames();
            for (String beanName : beanNames) {
                BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName);
                String className = beanDefinition.getBeanClassName();
                if (className == null) {
                    continue;
                }
                try {
                    Class<?> clazz = Class.forName(className);
                    String packageName = clazz.getPackage() != null ? clazz.getPackage().getName() : "";
                    for (String filter : filters) {
                        if (matchesPackage(packageName, filter)) {
                            System.out.println(className + " 设置为懒加载");
                            beanDefinition.setLazyInit(true);
                            break;
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        if (StringUtils.hasText(lazyClassFilter)) {
            String[] filters = lazyClassFilter.trim().split(",");
            String[] beanNames = configurableListableBeanFactory.getBeanDefinitionNames();
            for (String beanName : beanNames) {
                BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName);
                String className = beanDefinition.getBeanClassName();
                if (className == null) {
                    continue;
                }
                for (String filter : filters) {
                    if (className.equals(filter)) {
                        System.out.println(className + " 设置为懒加载");
                        beanDefinition.setLazyInit(true);
                        break;
                    }
                }
            }
        }

        if (StringUtils.hasText(lazyBeanNameFilter)) {
            String[] filters = lazyBeanNameFilter.trim().split(",");
            String[] beanNames = configurableListableBeanFactory.getBeanDefinitionNames();
            for (String beanName : beanNames) {
                BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName);
                for (String filter : filters) {
                    if (beanName.equals(filter)) {
                        System.out.println(beanName + " 设置为懒加载");
                        beanDefinition.setLazyInit(true);
                        break;
                    }
                }
            }
        }
    }

    private boolean matchesPackage(String targetPackage, String pattern) {
        if (pattern.endsWith(".*")) {
            // 匹配当前包下的一级类（不包括子包）
            String basePackage = pattern.substring(0, pattern.length() - 2);
            return targetPackage.equals(basePackage) || targetPackage.startsWith(basePackage + ".");
        } else {
            // 精确匹配包名
            return targetPackage.equals(pattern);
        }
    }
}
